from flask import Flask, request, render_template, make_response
import mysql.connector
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

from cStringIO import StringIO

years=[1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013]

# HTML template, we embed base64 encoded image data in the <img> HTML element
html = '''
<html>
    <body>
        <img src="data:image/png;base64,{}" />
    </body>
</html>
'''

app = Flask(__name__)
cnx=mysql.connector.connect(user='amanda', password='amanda', host='localhost',database='BartStats', )
cursor=cnx.cursor()


@app.route('/', methods=['GET'])

def hello_world():
    data=[line.strip() for line in open('/Users/amandaclark/PycharmProjects/BartStats/stations.txt', 'r')]
    return render_template('select.html', data=data)


@app.route('/graph', methods=['POST'])
def graph():
    numbers=list()
    station=request.form['station']
    query="SELECT * FROM stats WHERE station_name='%s'"% station
    cursor.execute(query)
    row=cursor.fetchall()
    num=len(row)
    foo=showGraph(row, num, station)
    return foo



def showGraph(row, num, station):

    fig = plt.figure()
    row[0]=row[0][1:]

    ax = fig.add_subplot(1, 1, 1)

    ax.plot(years, row[0][0:])

    ax.legend()
    plt.title('Average Weekday Ridership for %s'% station)
    # Encode image to png in base64
    io = StringIO()
    fig.savefig(io, format='png')
    data = io.getvalue().encode('base64')

    return html.format(data)





if __name__ == '__main__':

    app.debug=True
    app.run()
